<template>
  <div class="app-container" style="display: flex;gap: 20px;">
    <div style="width: 430px">
        <calendar @clickItem="clickItem" />
        <el-table
            :data="tableData"
            border
            style="width: 100%;margin-top: 20px">
            <el-table-column
            prop="date"
            label="当班时间"
            align="center">
                <template slot-scope="scope" >
                  <div v-if="scope.row.muyuanTeam">
                    <span >{{ scope.row.executeTeamStartTime }}</span> 至 <span>{{ scope.row.executeTeamEndTime }}</span>
                  </div>
                    <div v-else style="height: 30px;"></div>
                </template>
            </el-table-column>
            <el-table-column
            prop="muyuanTeam.teamName"
            width="200px"
            label="班组名称"
            align="center">
              <template slot-scope="scope">
                    <span>{{ scope.row.muyuanTeam && scope.row.muyuanTeam.teamName }}</span>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div style="flex: 1;">
      <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="当班时间" prop="executeTeamTime">
          <!-- <el-date-picker v-model="queryDateArr" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker> -->
          <el-date-picker
            v-model="queryParams.executeTeamTime"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="班组名称" prop="teamName">
          <el-input v-model="queryParams.teamName" placeholder="请输入班组名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="排班时间" prop="executeTeamTime">
            <el-date-picker clearable
            v-model="queryParams.executeTeamTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择排班时间">
            </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['system:team:add']">新增</el-button>
        </el-form-item>
      </el-form>
     
      <el-table v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="当班起止时间" align="center" width="360" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.executeTeamStartTime }}</span> 至 <span>{{ scope.row.executeTeamEndTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="当班班组" align="center" prop="muyuanTeam.teamName" show-overflow-tooltip/>
        <el-table-column label="班组负责人" align="center" prop="muyuanTeam.teamLeaderName" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.muyuanTeam ? scope.row.muyuanTeam.teamLeaderName : '' }}</span>-<span>{{ scope.row.muyuanTeam ? scope.row.muyuanTeam.teamLeaderPhone : ''
            }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="班组成员" align="center" prop="muyuanTeam.teamLeaderName">
            <template slot-scope="scope">
                <span>{{ scope.row.executeTeamStartTime }}</span>------<span>{{ scope.row.executeTeamEndTime }}</span>
            </template>
        </el-table-column> -->
        <el-table-column fixed="right" width="160" label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-if="(new Date(scope.row.executeTeamEndTime).getTime() >= new Date().getTime()  )" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:team:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:team:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>


    <!-- 添加或修改排班管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item :rules="[{ required: true, message: '请选择当班起止时间', trigger: 'blur' }]" label="当班起止时间"
          prop="executeTeamStartTime">
          <el-date-picker v-model="dateArr" type="daterange" range-separator="至" value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item :rules="[{ required: true, message: '请选择班组', trigger: 'blur' }]" label="选择班组" prop="teamId">
          <div style="display:flex;gap: 20px;align-items:center">
            <span v-if="form.teamInfo">{{ form.teamInfo.teamName }}</span>
            <el-button type="text" @click="dialogVisible = true">{{ form.teamId ? '请重新选择' : '请选择' }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <SelectTeamDialog :dialogVisible="dialogVisible" @onClose="dialogVisible = false" :isStatus="true" @onSubmit="selectTeam">
    </SelectTeamDialog>
  </div>
</template>

<script>
import { listTeam, getTeam, delTeam, addTeam, updateTeam } from "@/api/service/production/scheduling";
import SelectTeamDialog from "@/components/SelectDialog/SelectTeamDialog"
import calendar from './components/calendar'
export default {
  components: {
    SelectTeamDialog,
    calendar
  },
  name: "Team",
  data() {
    const now = new Date()
    return {
      value: now,
      tableData: [],
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排班管理表格数据
      teamList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamId: null,
        executeTeamTime: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

    };
  },
  computed: {
    queryDateArr: {
      get() {
        if (this.queryParams?.executeTeamStartTime) {
          return [this.queryParams?.executeTeamStartTime, this.queryParams?.executeTeamEndTime]
        }
        return []
      },
      set(value) {
        this.queryParams.executeTeamStartTime = value[0]
        this.queryParams.executeTeamEndTime = value[1]
      }
    },
    dateArr: {
      get() {
        if (this.form?.executeTeamStartTime) {
          return [this.form?.executeTeamStartTime, this.form?.executeTeamEndTime]
        }
        return []
      },
      set(value) {
        this.form.executeTeamStartTime = value[0]
        this.form.executeTeamEndTime = value[1]
      }
    }
  },
  created() {
    this.getList();

    this.initTable()
  },
  methods: {
    async initTable() {
        const now = new Date()
        const date = `${now.getFullYear()}-${ (now.getMonth() + 1).toString().padStart(2, 0) }-${ now.getDate().toString().padStart(2, 0) }`
        const next = new Date( new Date(date).getTime() + ( 1000 * 60 * 60 *24 ) ) 
        const res = await listTeam({
            executeTeamStartTime: date,
            executeTeamEndTime: `${next.getFullYear()}-${ (next.getMonth() + 1).toString().padStart(2, 0) }-${ next.getDate().toString().padStart(2, 0) }`,
        })
        this.tableData = res.rows
    },
    async clickItem(date){
        //const next = new Date( new Date(date).getTime() + ( 1000 * 60 * 60 *24 ) ) 
        const res = await listTeam({
            // executeTeamStartTime: date,
            // executeTeamEndTime: `${next.getFullYear()}-${ (next.getMonth() + 1).toString().padStart(2, 0) }-${ next.getDate().toString().padStart(2, 0) }`,
            executeTeamTime:  date,
        })
        this.tableData = res.rows
    },
    selectTeam(row) {

      this.form.teamInfo = row
      this.form.teamId = row.teamId
      this.$refs.form.validateField('teamId')
    },
    /** 查询排班管理列表 */
    getList() {
      this.loading = true;
      listTeam(this.queryParams).then(response => {
        this.teamList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sortTeamId: null,
        teamId: null,
        teamInfo: null,
        executeTeamStartTime: null,
        executeTeamEndTime: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sortTeamId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增排班管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sortTeamId = row.sortTeamId || this.ids
      getTeam(sortTeamId).then(response => {
        this.form = {
          ...response.data,
          teamInfo: row.muyuanTeam
        }
        this.open = true;
        this.title = "修改排班管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sortTeamId != null) {
            updateTeam(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeam(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sortTeamIds = row.sortTeamId || this.ids;
      this.$modal.confirm('是否确认删除排班管理编号为"' + sortTeamIds + '"的数据项？').then(function () {
        return delTeam(sortTeamIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/team/export', {
        ...this.queryParams
      }, `team_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
